<template>
  <div class="view-fill">
    <div v-if="!changeAnalysisInfo.visible" class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        :title="title"
        @returnBack="$emit('returnModify')"
      >
        <template v-slot:full-button>
          <el-button @click="save()">保存</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <PageForm
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-planName>
                <el-input
                  v-model="formInfo.data.planName"
                  :class="orderId ? '' : 'not-mongolia'"
                  type="input"
                  :required="true"
                  :disabled="true"
                  :placeholder="'请选择分析方案名称'"
                >
                  <template v-if="!orderId" #append>
                    <el-icon @click="checkAnalysisInfo"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
            </PageForm>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>分析设备详细信息</p>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <el-form :model="tableInfo" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :checkBox="false"
                  :tab-index="true"
                  :field-list="tableInfo.fieldList"
                  :isDynamic="false"
                >
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>费用支出明细信息</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <PageFilter :filter-list="filterInfo.list">
              <template v-slot:filter-addTableAsset>
                <el-button :disabled="!canAddAsset" @click="addTableAsset"
                  >新增行</el-button
                >
              </template>
              <template v-slot:filter-removeAsset>
                <el-button :disabled="!canRemoveAsset" @click="removeAsset()"
                  >删除行</el-button
                >
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form
                ref="tableForm"
                :model="tablePriceInfo"
                style="width: 100%"
              >
                <!-- 表格 -->
                <PageTable
                  :refresh="tablePriceInfo.refresh"
                  :init-curpage="tablePriceInfo.initCurpage"
                  v-model:data="tablePriceInfo.data"
                  :pager="false"
                  :tab-index="true"
                  :field-list="tablePriceInfo.fieldList"
                  :handle="tablePriceInfo.handle"
                  :row-class-name="tableRowClassName"
                  :isRowClickSelect="true"
                  :check-box="true"
                  rowKey="randomNumber"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-costProject="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.costProject`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择支出项目名称',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <SelectModel
                        v-model="scope.row.costProject"
                        type-code="asset_cost_project"
                        placeholder="请选择支出项目名称"
                        :optionDisabled="
                          getCostProjectDisabledList(scope.row.costProject)
                        "
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.costProject`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-calcRule="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}.calcRule`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择计算规则',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <SelectModel
                        v-model="scope.row.calcRule"
                        type-code="calc_rule_enum"
                        placeholder="请选择计算规则"
                        :onlyShowOption="getShowList(scope.row)"
                        @change="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.calcRule`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                  <template v-slot:col-costAmount="scope">
                    <el-form-item
                      v-if="scope.$index >= 0 && scope.row.calcRule != '2'"
                      :prop="`data.${scope.$index}.costAmount`"
                      :rules="[
                        {
                          required: true,
                          message: '请输入支出金额',
                          trigger: ['blur', 'change'],
                        },
                      ]"
                      @click.stop=""
                    >
                      <el-input-number
                        style="width: 100%"
                        v-model.lazy="scope.row.costAmount"
                        clearable
                        controls-position="right"
                        :precision="2"
                        :min="0"
                        :max="99999999"
                        @input="
                          changeValidate(
                            $event,
                            `data.${scope.$index}.costAmount`,
                            'tableForm'
                          )
                        "
                      />
                    </el-form-item>
                  </template>
                </PageTable>
              </el-form>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>
    <!-- 选择方案 -->
    <ChangeAnalysisPlans
      v-if="changeAnalysisInfo.visible"
      v-model:visible="changeAnalysisInfo.visible"
      :query="changeAnalysisInfo.query"
      @callback="callbackAnalysisPlans"
      @returnBack="returnBackAnalysisPlans"
    />
  </div>
</template>

<script setup name="assetCostConfigModify">
const ChangeAnalysisPlans = defineAsyncComponent(() =>
  import('@/views/asset/analy/assetItemBinding/changeAnalysisPlans')
)
import {
  postAnalysisCostConfig,
  putAnalysisCostConfig,
  getAnalysisPlanById,
  getAnalysisPlanDetailById,
  getAnalysisCostConfigDetail,
  getAnalysisCostConfigById,
} from '@/api/asset'
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'orderId', 'id'])

//表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    {
      label: '分析方案名称',
      value: 'planName',
      type: 'slot',
    },
    {
      label: '分析方案编码',
      value: 'planNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '分析部门',
      value: 'deptName',
      type: 'input',
      disabled: true,
    },
    {
      label: '分析类型',
      value: 'analysisTypeValue',
      type: 'input',
      disabled: true,
    },
    {
      label: '收入/成本摊销方式',
      value: 'amortizationMethodValue',
      type: 'input',
      disabled: true,
    },
  ],
  rules: {
    planName: [
      {
        required: true,
        message: '请选择分析方案名称',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '180px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    { type: 'slot', value: 'addTableAsset' },
    { type: 'slot', value: 'removeAsset' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    {
      label: '资产卡片号',
      value: 'assetCode',
    },
    {
      label: '资产名称',
      value: 'assetName',
    },
    { label: '规格', value: 'standard' },
    { label: '厂家', value: 'brandName' },
    { label: '供应商', value: 'supplierName' },
    {
      label: '收入/成本摊销比例(%)',
      value: 'amortizationRate',
    },
    {
      label: '预计检查(治疗)人次/月',
      value: 'estimateTreatPersonTime',
    },
    {
      label: '预计检查(治疗)收入/月',
      value: 'estimateTreatIncome',
    },
    {
      label: '预计开机时长/月',
      value: 'estimatePowerUp',
    },
  ],
})
const tablePriceInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '支出项目名称', value: 'costProject', type: 'slot' },
    { label: '计算规则', value: 'calcRule', type: 'slot' },
    { label: '支出金额', value: 'costAmount', type: 'slot' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '添加行',
        event: addAssetRow,
        show: true,
      },
      {
        label: '删除',
        event: removeAsset,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
      {
        label: '对接配置',
        event: settingConsumables,
        show: true,
        ifRender: settingIfRender,
      },
    ],
  },
})
const changeAnalysisInfo = ref({
  visible: false,
  query: {
    costConfigQueryNot: 1,
  },
})
const currentInfo = ref({})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canAddAsset = computed(() => {
  return formInfo.value.data.planNo
})
const canRemoveAsset = computed(() => {
  return tablePriceInfo.value.selections.length
})

onMounted(() => {
  if (props.id) {
    getMain()
  }
})

function getCostProjectDisabledList(code) {
  const tableCodeArr = []
  tablePriceInfo.value.data.forEach((item) => {
    if (item.costProject && item.costProject != code) {
      tableCodeArr.push(item.costProject)
    }
  })
  return tableCodeArr
}
function settingIfRender(row) {
  const dictArr = ['materialAmount', 'labourAmount', 'drugAmount']
  return dictArr.includes(row.costProject) && row.calcRule == 2
}
function getShowList(row) {
  const dictArr = [
    'depreciationAmount',
    'repairAmount',
    'maintenanceAmount',
    'materialAmount',
    'labourAmount',
    'drugAmount',
  ]
  if (dictArr.includes(row.costProject)) {
    return ['0', '1', '2']
  } else {
    if (row.calcRule === '2') {
      row.calcRule = ''
    }
    return ['0', '1']
  }
}
function checkAnalysisInfo() {
  changeAnalysisInfo.value.visible = true
}
function callbackAnalysisPlans(obj) {
  formInfo.value.data = obj.selectData
  tableInfo.value.data = obj.detailsDate
  changeAnalysisInfo.value.visible = false
}
function returnBackAnalysisPlans() {
  changeAnalysisInfo.value.visible = false
}
function changeValidate(value, str, ref) {
  setTimeout(() => {
    proxy.$refs[ref].clearValidate(str)
  }, 30)
}
function getMain() {
  getAnalysisPlanById(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data
    }
  })
  getAnalysisPlanDetailById({ analysisPlanId: props.orderId }).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
  getAnalysisCostConfigDetail({ costConfigId: props.id }).then((res) => {
    if (res && res.success) {
      tablePriceInfo.value.data = res.data
      tablePriceInfo.value.data.forEach((item, index) => {
        item.randomNumber = new Date().getTime() + index
      })
    }
  })
  getAnalysisCostConfigById({ id: props.id }).then((res) => {
    if (res && res.success) {
      currentInfo.value = res.data
    }
  })
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return 'success-row'
  } else {
    return ''
  }
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tablePriceInfo.value.selections = [...data]
      break
  }
}
function save() {
  if (!tablePriceInfo.value.data || tablePriceInfo.value.data.length === 0) {
    proxy.$message.warning('请添加项目！')
    return
  }
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      proxy.$refs.tableForm.validate((valid2) => {
        if (valid2) {
          const api = props.orderId
            ? putAnalysisCostConfig
            : postAnalysisCostConfig
          api({
            id: props.id,
            analysisPlanId: formInfo.value.data.id,
            details: tablePriceInfo.value.data,
            version: currentInfo.value.version,
          }).then((res) => {
            if (res && res.success) {
              showDialog.value = false
              proxy.$emit('returnModify', false)
            }
          })
        } else {
          proxy.$message.warning('请按照提示输入正确数据')
        }
      })
    } else {
      proxy.$message.warning('请按照提示输入正确数据')
    }
  })
}
function addTableAsset() {
  const randomNumber = new Date().getTime()
  tablePriceInfo.value.data.push({
    randomNumber: randomNumber,
  })
}
//选择资产
function addAssetRow(row) {
  const randomNumber = new Date().getTime()
  const tableIndex = tablePriceInfo.value.data.findIndex((item) => {
    return item.randomNumber === row.randomNumber
  })
  const tableData = proxy.$fn.deepClone(tablePriceInfo.value.data)
  tableData.splice(tableIndex + 1, 0, {
    randomNumber: randomNumber,
  })
  tablePriceInfo.value.data = tableData
}
//删除资产
function removeAsset(selectRow = undefined) {
  if (selectRow) {
    tablePriceInfo.value.data = tablePriceInfo.value.data.filter(
      (row) => row != selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        const tempData = tablePriceInfo.value.data.filter(
          (row) => !tablePriceInfo.value.selections.includes(row)
        )
        tablePriceInfo.value.data = tempData
      })
  }
}
function settingConsumables(row) {
  if (row.costProject === 'materialAmount') {
    proxy.$router.push('/asset/analy/assetConsumables')
  } else if (row.costProject === 'labourAmount') {
    proxy.$router.push('/asset/analy/assetArtificial')
  } else if (row.costProject === 'drugAmount') {
    proxy.$router.push('/asset/analy/assetDrug')
  }
}
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow: hidden;
}
:deep(.model-panel-body) .filter-item {
  .el-form-item--default.el-form-item {
    margin-top: 6px;
    margin-bottom: 6px;
  }
}
</style>
